<template>
  <div class="chat-container">
    <el-card class="chat-card">
      <template #header>
        <div class="chat-header">
          <div class="header-left">
            <el-button @click="$router.push('/')" text>
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            <h2>AI 聊天助手</h2>
          </div>
          <div class="header-right">
            <el-button type="danger" @click="clearChat" :disabled="!chatStore.messages.length">
              <el-icon><Delete /></el-icon>
              清空对话
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="chat-messages" ref="messagesContainer">
        <div v-if="!chatStore.messages.length" class="empty-state">
          <el-empty description="开始一段新的对话吧" />
        </div>
        <div v-else v-for="(message, index) in chatStore.messages" 
             :key="index" 
             :class="['message', message.role]">
          <div class="message-avatar">
            <el-avatar :size="40" :icon="message.role === 'user' ? 'User' : 'Service'" />
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
      </div>
      
      <div class="chat-input">
        <el-input
          v-model="userInput"
          type="textarea"
          :rows="3"
          :maxlength="1000"
          show-word-limit
          resize="none"
          placeholder="请输入您的问题... (Ctrl + Enter 发送)"
          @keyup.enter.ctrl="sendMessage"
        />
        <el-button 
          type="primary" 
          :loading="chatStore.loading"
          :disabled="!userInput.trim()"
          @click="sendMessage"
        >
          <el-icon><Position /></el-icon>
          发送
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useChatStore } from '../stores/chat'
import { chatService } from '../api/chat'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Delete, Position } from '@element-plus/icons-vue'

const chatStore = useChatStore()
const userInput = ref('')
const messagesContainer = ref(null)

const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const sendMessage = async () => {
  if (!userInput.value.trim()) return
  
  const message = userInput.value
  userInput.value = ''
  
  const userMessage = { 
    role: 'user', 
    content: message,
    timestamp: new Date().toISOString()
  }
  chatStore.addMessage(userMessage)
  await scrollToBottom()
  
  try {
    chatStore.setLoading(true)
    const response = await chatService.sendMessage(message)
    const assistantMessage = {
      role: 'assistant',
      content: response,
      timestamp: new Date().toISOString()
    }
    chatStore.addMessage(assistantMessage)
  } catch (error) {
    ElMessage.error('发送消息失败，请重试')
  } finally {
    chatStore.setLoading(false)
    await scrollToBottom()
  }
}

const clearChat = () => {
  ElMessageBox.confirm(
    '确定要清空所有对话记录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    chatStore.clearMessages()
    ElMessage.success('对话已清空')
  }).catch(() => {})
}

onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.chat-card {
  width: 100%;
  max-width: 800px;
  height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-left h2 {
  margin: 0;
  font-size: 1.2rem;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background-color: #f9f9f9;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 85%;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.message-text {
  padding: 12px 16px;
  border-radius: 12px;
  font-size: 0.95rem;
  line-height: 1.5;
  word-break: break-word;
}

.message.user .message-text {
  background-color: #409eff;
  color: white;
  border-top-right-radius: 4px;
}

.message.assistant .message-text {
  background-color: white;
  color: #333;
  border-top-left-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.message-time {
  font-size: 0.75rem;
  color: #909399;
  padding: 0 4px;
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  gap: 10px;
  background-color: white;
}

.chat-input .el-button {
  align-self: flex-end;
  padding: 12px 20px;
}

.chat-input .el-textarea {
  flex: 1;
}

:deep(.el-textarea__inner) {
  padding: 12px;
  font-size: 0.95rem;
  line-height: 1.5;
  border-radius: 8px;
  resize: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

:deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style> 